<template>
    <el-dialog :title="title" v-model="visible" width="480px" :close-on-click-modal="false" @close="emits('close')">
        <el-form ref="formRef"
                 :model="form"
                 :rules="formRules"
                 :label-width="140">
            <el-form-item label="赠送角色:">
                <el-select v-model="form.agent_type" placeholder="请选择赠送角色" @change="agentChange" v-if="props.state == 'add'">
                    <el-option v-for="(item,index) in dict['agent_type_list']" :key="index" :label="item.text" :value="item.value"></el-option>
                </el-select>
                <div v-else>{{ form.agent_type_desc }}</div>
            </el-form-item>
            <el-form-item label="赠送人姓名:">
                <el-select v-model="form.agent_id" placeholder="请选择赠送人" v-if="props.state == 'add'">
                    <el-option v-for="(item,index) in userList" :key="index" :label="item.real_name + ' | ' + item.mobile" :value="item.id"></el-option>
                </el-select>
                <div v-else>{{ form.real_name + ' | ' + form.mobile }}</div>
            </el-form-item>
            <el-tabs v-model="activeName" type="card" v-if="props.state == 'add' || props.state == 'edit'">
                <el-tab-pane v-for="(item,index) in dict['give_biz_type_list']" :key="index" :label="item.text" :name="item.value">
                    <div v-if="form.region_biz_list.length > 0 && form.region_biz_list[index].region_list.length > 0">
                        <el-form-item label="赠送分成比例:">
                            <div>{{ form.region_biz_list[index].rate }}%</div>
                            
                        </el-form-item>
                        <el-form-item label="赠送区域:">
                            <div>
                                <div style="display: flex; align-items: center; margin-bottom: 10px;" 
                                    v-for="(area_item, area_index) in form.region_biz_list[index].region_list" 
                                    :key="area_index">
                                    {{ area_item.province_name + area_item.city_name +  area_item.area_name}}
                                </div>
                            </div>
                            
                        </el-form-item>
                    </div>
                    <div v-else>暂未设置数据</div>
                </el-tab-pane>
            </el-tabs>
            <el-tabs v-model="activeName" type="card" v-if="props.state == 'give'">
                <el-tab-pane v-for="(item,index) in dict['give_biz_type_list']" :key="index" :label="item.text" :name="item.value">
                    <div v-if="form.seller_biz_list.length > 0 && form.seller_biz_list[index].seller_list.length > 0">
                        <el-form-item label="赠送分成比例:">                  
                            <div>{{ form.seller_biz_list[index].rate }}%</div>
                        </el-form-item>
                        <el-form-item label="赠送商家:">
                            <div>
                                <div style="display: flex; align-items: center; margin-bottom: 10px;" 
                                     v-for="(seller, seller_index) in form.seller_biz_list[index].seller_list" 
                                     :key="seller_index">
                                    {{ seller.company_name }}
                                </div>
                            </div>
                            
                        </el-form-item>
                    </div>
                    <div v-else>暂未设置数据</div>

                </el-tab-pane>
            </el-tabs>
            <!-- <div class="tab-list">
                <div class="tab-item" v-for="(item, index) in dict['give_biz_type_list']" :key="index"></div>
            </div> -->
        </el-form>

        
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick, onMounted} from 'vue'
import { ElMessage } from 'element-plus'

import type { FormInstance, FormRules, CascaderProps } from 'element-plus'

import { getGiveDetail, addGive, editGive,setGive } from 'services/setting'

import { getRegion,getSellerList } from 'services/system'

import { getAgentPartnerList,getAgentServiceList } from 'services/common'

import systemStore from '@/store/modules/system'

const $systemStore = systemStore()

const emits = defineEmits(['close', 'success'])

const formRef = ref<FormInstance>()

const activeName = ref<any>('1')

export interface AgentType {
    biz_type:any,
    rate:any,
    area_ids?:any[],
    seller_ids?:any[]
}

const form = ref({
    id: undefined,
    agent_type: '',
    agent_id: '',
    agent_type_desc:'',
    real_name:'',
    mobile:'',
    region_biz_list:<any[]>[],
    seller_biz_list:<any[]>[]
})

const checkPhone = (rule:any,value:any,callback:any) => {
    let reg = /^1[0-9]{10}$/;
    
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const formRules = reactive<FormRules>({
   
})

const props = defineProps<{
    dialogVisible:boolean,
    id?:number,
    state:string
}>();

const visible = ref(false)


const agentChange = (val:any) => {
    getInfo(val)
}

watch(() => props.dialogVisible, async (val) => {
    visible.value = val
    if (visible.value === true) {
        await nextTick()
        if (props.state == 'edit' || props.state == 'give') {
            if (props.id) {
               
                getDetail(props.id)
            }
        } 
    }
},{
    immediate:true
})

const title = computed(() => {
    let str = ''
    if (props.state == 'add') {
        str = '新增'
    }

    if (props.state == 'edit') {
        str = '赠送区域'
    }

    if (props.state == 'give') {
        str = '赠送商家'
    }
    return str
})

const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            let data = JSON.parse(JSON.stringify(form.value))
            if (props.state == 'edit' || props.state == 'add') {
                data.biz_set_list.forEach((item:any,index:any) => {
                    item.area_ids.forEach((sub:any, subIndex:any) => {
                        if (sub.length > 0) {
                            data.biz_set_list[index].area_ids[subIndex] = sub[2]
                        } else {
                            data.biz_set_list[index].area_ids[subIndex] = ''
                        }
                    })
                })
            }
            

            if (data.id) {
                if (props.state == 'edit') {
                    editGive(data).then(res => {
                        ElMessage.success('操作成功')
                        emits('success')
                    })
                } 

                if (props.state == 'give') {
                    setGive(data).then(res => {
                        ElMessage.success('操作成功')
                        emits('success')
                    })
                }
                
            } else {
                addGive(data).then(res => {
                    ElMessage.success('操作成功')
                    emits('success')
                })
            }
           
        } else {
            console.log('error submit', fields)
        }
    }) 
}

const getDetail = (id:number) => {
    getGiveDetail({id}).then((res:any) => {
        let data = res
        
        form.value.id = data.id
        form.value.agent_type_desc = data.agent_type_desc
        form.value.real_name = data.real_name
        form.value.mobile = data.mobile
        form.value.region_biz_list = data.region_biz_list
        form.value.seller_biz_list = data.seller_biz_list
    })
}

const sellerArray = ref(<any>[])


const userList = ref<any[]>([])

const getInfo = (val:any) => {
    if (val == 1) {
        getAgentPartnerList({}).then(res => {
            form.value.agent_id = ''
            userList.value = res.items
        })
    }  

    if (val == 2) {
        getAgentServiceList().then(res => {
            form.value.agent_id = ''
            userList.value = res.items
        })
    }
  
}

const dict = computed<any>(() => {
    return $systemStore.dict
})

onMounted(() => {
    // getInfo()
    // getRoleData()
    // getDepartData()
})
</script>